package com.zz.hhbl.utils.location

import android.app.Application
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.utils.language.Strings
import com.zz.hhbl.config.GlobalCache
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/24 17:36.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
class LocationRepository(private val application: Application) : DefaultLifecycleObserver {
    private var _locationFlow = MutableStateFlow<LocationResult?>(null)
    val locationFlow: StateFlow<LocationResult?> = _locationFlow.asStateFlow()
    private val context = application.applicationContext

    private val locationClient by lazy {
        //必须先要设置阅读隐私协议
        AMapLocationClient.updatePrivacyShow(context, true, true)
        AMapLocationClient.updatePrivacyAgree(context, true)
        AMapLocationClient(context)
    }


    init {
        locationClient.setLocationListener { location ->
            if (location != null && location.errorCode == 0) {
                GlobalCache.setLongitude(location.latitude)
                GlobalCache.setLatitude(location.latitude)
                val newResult = LocationResult(
                    latitude = location.latitude,
                    longitude = location.longitude,
                    address = location.address ?: Strings.未知地址.toLanguage(),
                    country = location.country ?: Strings.未知.toLanguage(),
                    province = location.province ?: Strings.未知.toLanguage(),
                    city = location.city ?: Strings.未知.toLanguage(),
                    district = location.district ?: Strings.未知.toLanguage(),
                    street = location.street ?: Strings.未知.toLanguage(),
                    streetNumber = location.streetNum ?: Strings.未知.toLanguage()
                )
                _locationFlow.tryEmit(newResult)
            }
        }
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    fun startLocation(
        locationOption: AMapLocationClientOption = AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            isOnceLocation = false
            interval = 30 * 60 * 1000L //30分钟一次
        }
    ) {
        if (XXPermissions.isGranted(context, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) {
            locationClient.setLocationOption(locationOption)
            locationClient.startLocation()
        } else {
            XXPermissions.with(application).permission(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION).request { permissions, allGranted ->
                run {
                    if (allGranted) {
                        locationClient.setLocationOption(locationOption)
                        locationClient.startLocation()
                    }
                }
            }
        }

    }

    fun stopLocation() {
        locationClient.stopLocation()
    }

    override fun onStop(owner: LifecycleOwner) {
        stopLocation() // 后台自动停止
    }

    fun release() {
        locationClient.onDestroy()
        ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
    }

    /**
     * **获取单次定位**
     */
    suspend fun getSingleLocation(): Result<LocationResult?> = suspendCancellableCoroutine { cont ->
        if (!XXPermissions.isGranted(context, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) {
            cont.resumeWith(Result.failure(Exception(Strings.缺少定位权限.toLanguage())))
            return@suspendCancellableCoroutine
        }
        val tempClient = AMapLocationClient(context)
        val tempOption = AMapLocationClientOption().apply { isOnceLocation = true }
        tempClient.setLocationListener { location ->
            if (location != null && location.errorCode == 0) {
                GlobalCache.setLongitude(location.latitude)
                GlobalCache.setLatitude(location.latitude)
                val result = LocationResult(
                    latitude = location.latitude,
                    longitude = location.longitude,
                    address = location.address ?: Strings.未知地址.toLanguage(),
                    country = location.country ?: Strings.未知.toLanguage(),
                    province = location.province ?: Strings.未知.toLanguage(),
                    city = location.city ?: Strings.未知.toLanguage(),
                    district = location.district ?: Strings.未知.toLanguage(),
                    street = location.street ?: Strings.未知.toLanguage(),
                    streetNumber = location.streetNum ?: Strings.未知.toLanguage()
                )
                cont.resume(Result.success(result))
            } else {
                cont.resume(Result.success(LocationResult(latitude = GlobalCache.getLatitude(), longitude = GlobalCache.getLongitude())))
            }
            tempClient.onDestroy()
        }
        tempClient.setLocationOption(tempOption)
        tempClient.startLocation()
    }
}

/**
 * **定位返回数据**
 */
data class LocationResult(
    val latitude: Double,
    val longitude: Double,
    val address: String = "",
    val country: String = "",
    val province: String = "",
    val city: String = "",
    val district: String = "",
    val street: String = "",
    val streetNumber: String = ""
) {
    override fun equals(other: Any?): Boolean {
        //这样会每次都变化
        return false
    }
}